<template>
  <div class="app-container" v-loading="loading">
    <template v-if="!loading && app">
      <iframe
        ref="appFrame"
        :src="appUrl"
        class="app-iframe"
        sandbox="allow-scripts allow-same-origin"
        @load="handleIframeLoad"
      ></iframe>
    </template>
    <el-empty v-else-if="!loading && !app" description="应用不存在或已下架" />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useAppStore } from '@/stores/app'
import { useUserStore } from '@/stores/user'

const route = useRoute()
const appStore = useAppStore()
const userStore = useUserStore()

const loading = ref(true)
const app = ref<any>(null)
const appFrame = ref<HTMLIFrameElement | null>(null)
const appUrl = ref('')

// SDK暴露的方法
const exposedMethods = {
  getCurrentUser: () => userStore.userInfo,
  getAppInfo: () => app.value,
  // 可以添加更多方法，如API请求代理等
}

// 处理iframe加载完成
const handleIframeLoad = () => {
  if (appFrame.value) {
    // 注入SDK
    injectSDK()
  }
}

// 注入SDK
const injectSDK = () => {
  if (!appFrame.value || !appFrame.value.contentWindow) return
  
  try {
    // 创建SDK对象
    const sdk = {
      version: '1.0.0',
      ...exposedMethods,
    }
    
    // 注入SDK到iframe
    appFrame.value.contentWindow.postMessage({
      type: 'SDK_INIT',
      data: sdk,
    }, '*')
    
    console.log('SDK已注入到应用', app.value?.name)
  } catch (error) {
    console.error('注入SDK失败', error)
    ElMessage.error('应用加载失败，请刷新页面重试')
  }
}

// 处理来自iframe的消息
const handleMessage = (event: MessageEvent) => {
  // 验证消息来源
  if (!appFrame.value || event.source !== appFrame.value.contentWindow) return
  
  const { type, data } = event.data
  
  // 处理不同类型的消息
  switch (type) {
    case 'SDK_READY':
      // 应用已准备好接收SDK
      injectSDK()
      break
    case 'API_REQUEST':
      // 处理API请求
      handleApiRequest(data)
      break
    default:
      break
  }
}

// 处理API请求
const handleApiRequest = async (data: any) => {
  if (!appFrame.value || !appFrame.value.contentWindow) return
  
  try {
    // 这里可以添加权限验证逻辑
    
    // 发送响应回应用
    appFrame.value.contentWindow.postMessage({
      type: 'API_RESPONSE',
      requestId: data.requestId,
      data: { success: true, message: '请求成功' },
    }, '*')
  } catch (error) {
    console.error('处理API请求失败', error)
    
    // 发送错误响应
    if (appFrame.value && appFrame.value.contentWindow) {
      appFrame.value.contentWindow.postMessage({
        type: 'API_RESPONSE',
        requestId: data.requestId,
        error: '请求失败',
      }, '*')
    }
  }
}

// 获取应用信息
const fetchAppInfo = async () => {
  loading.value = true
  try {
    const appId = parseInt(route.params.id as string)
    const appInfo = await appStore.fetchAppDetail(appId)
    
    if (appInfo) {
      app.value = appInfo
      // 构建应用URL
      appUrl.value = appInfo.storagePath || `/apps/${appInfo.id}/index.html`
    } else {
      app.value = null
    }
  } catch (error) {
    console.error('获取应用信息失败', error)
    app.value = null
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  fetchAppInfo()
  
  // 添加消息监听
  window.addEventListener('message', handleMessage)
})

onUnmounted(() => {
  // 移除消息监听
  window.removeEventListener('message', handleMessage)
})
</script>

<style scoped>
.app-container {
  width: 100%;
  height: 100%;
  overflow: hidden;
}

.app-iframe {
  width: 100%;
  height: 100%;
  border: none;
}
</style> 